﻿// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232509
(function () {
    "use strict";

    WinJS.Binding.optimizeBindingReferences = true;

    var app = WinJS.Application;
    var activation = Windows.ApplicationModel.Activation;
    var db = null;
    var isNew = false;

    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                // TODO: This application has been newly launched. Initialize
                // your application here.
            } else {
                // TODO: This application has been reactivated from suspension.
                // Restore application state here.
            }
            args.setPromise(WinJS.UI.processAll());

            init();

            var createButton = document.getElementById("createDB");
            createButton.addEventListener("click", createDB, false)

            var deleteButton = document.getElementById("deleteDB");
            deleteButton.addEventListener("click", deleteDB, false)

            var saveButton = document.getElementById("savedata");
            saveButton.addEventListener("click", writeData, false)
            readData();
        }
    };

    app.oncheckpoint = function (args) {
        // TODO: This application is about to be suspended. Save any state
        // that needs to persist across suspensions here. You might use the
        // WinJS.Application.sessionState object, which is automatically
        // saved and restored across suspension. If you need to complete an
        // asynchronous operation before your application is suspended, call
        // args.setPromise().
    };

    WinJS.Namespace.define("Calendar", {
        db: db
    });

    function createDB() {
        // Create the request to open the database, named CalendarNoteDB. If it doesn't exist, create it and immediately
        // upgrade to version 1.
        var dbRequest = window.indexedDB.open("CalendarNoteDB", 1);

        // Add asynchronous callback functions
        dbRequest.onerror = function () {
            log("db create request error");
        };
        dbRequest.onsuccess = function (evt) {

            if (!isNew) {
                log("db already exist");

            }
            else {
                log("db create request success");
            }
            readData();
            evt.target.result.close();
        };
        dbRequest.onupgradeneeded = function (evt) {
            var sampledata = { title: "the event title", date: "20130102", content: "the event content", isNotify: true };
            // Get the version update transaction handle, since we want to create the schema as part of the same transaction.
            var txn = evt.target.transaction;

            // Create the note object store, with an index on the book title. Note that we set the returned object store to a variable
            // in order to make further calls (index creation) on that object store.
            var noteStore = evt.target.result.createObjectStore("Notes", { keyPath: "id", autoIncrement: true });
            noteStore.createIndex("IndexByTitle", "title", { unique: false });
            noteStore.createIndex("IndexByDate", "date", { unique: false });


            var addResult = noteStore.add(sampledata);

            // Once the creation of the object stores is finished (they are created asynchronously), log success.
            txn.oncomplete = function () {
                log("Database schema created.");
                txn.db.close();
            };

            isNew = true;
        };
        dbRequest.onblocked = function () {
            log("db create request blocked");
        };

        isNew = false;
    }

    function deleteDB() {
        var dbRequest = window.indexedDB.deleteDatabase("CalendarNoteDB");
        dbRequest.onerror = function () {
            log("Error deleting database.");
        };
        dbRequest.onsuccess = function () {
            log("db deleted");
            var outputDiv = document.getElementById("dbcontent");
            outputDiv.innerHTML = "";
        };
        dbRequest.onblocked = function () {
            log("Database delete blocked.");
        };
    }

    function writeData() {
        var dbRequest = window.indexedDB.open("CalendarNoteDB", 1);
        dbRequest.onsuccess = function (evt) {
            var data = document.getElementById("datainput").value;

            if (evt.target.result.objectStoreNames.length < 1) {
                log("Database schema does not exist, create db first")
                return;
            }

            // Create a transaction to write the changes to the database        
            var txn = evt.target.result.transaction(["Notes"], "readwrite");

            // Set the event callbacks for the transaction
            txn.onerror = function (evt) { log("Error writing data."); };
            txn.onabort = function (evt) { log("Writing of data aborted."); };

            // The oncomplete event handler is called asynchronously once all writes have completed; when that's done, we reset our pending write queue.
            txn.oncomplete = function () {
                // pendingWrites = [];
                log("Changes saved to database.");
                readData();
                txn.db.close();
            };

            var noteStore = txn.objectStore("Notes");

            var addResult = noteStore.add({ title: data, "date": "20130101" });
            addResult.onerror = function (evt) { log("Error adding data."); }
        }
    }


    function readData(evt) {
        var dbRequest = window.indexedDB.open("CalendarNoteDB", 1);
        dbRequest.onsuccess = function (evt) {
            if (evt.target.result.objectStoreNames.length < 1) {
                log("no read, Database schema does not exist, create db first")
                evt.target.result.close();
                return;
            }

            // Declare arrays to hold the data to be read.
            var notes = [];
            var txn = evt.target.result.transaction(["Notes"], "readonly");

            // Set the event callbacks for the transaction.
            txn.onerror = function () { log("Error reading data."); };
            txn.onabort = function () { log("Reading of data aborted."); };

            // The oncomplete event handler is called asynchronously once reading is finished and the data arrays are fully populated. This
            // completion event will occur later than the cursor iterations defined below, because the transaction will not complete until
            // the cursors are finished.
            txn.oncomplete = function () {
                var outputContent = "";

                // If there are no notes to display, there is no need to continue.
                var len = notes.length;
                if (len === 0) {
                    return;
                }

                // Construct an output table with one row per book.
                for (i = 0; i < len; i++) {
                    outputContent += "<div>title:" + notes[i].title + ",date:" + notes[i].date + ",isNotify:" + notes[i].isNotify + "</div>";
                    document.getElementById(notes[i].date).parentElement.parentElement.className = "event";
                }

                // Display the content.
                var outputDiv = document.getElementById("dbcontent");
                outputDiv.innerHTML = outputContent;
                txn.db.close();
            };

            // Create a cursor on the notes object store. Because we want the results to be returned in title order, we use the title index
            // on the object store for the cursor to operate on. We could pass a keyRange parameter to the openCursor call to filter the cursor
            // to specific titles.
            //var noteCursorRequest = txn.objectStore("Notes").index("title").openCursor();
            var noteObjectStore = txn.objectStore("Notes");

            //var boundKeyRange = IDBKeyRange.lowerBound("app", true);
            //var noteCursorRequest = noteObjectStore.index("IndexByTitle").openCursor(boundKeyRange, "next");
            var noteCursorRequest = noteObjectStore.index("IndexByTitle").openCursor();

            var oGetInex = noteObjectStore.index("IndexByTitle");
            var oGet = oGetInex.get("app");
            oGet.onsuccess = function (e) {
                var o = e.target.result;
            }
            //var oIndexApp = noteObjectStore.index("app");
            var oCount = noteObjectStore.count();
            oCount.onsuccess = function (e) {
                var r = e.target.result;
            }

            // As each record is returned (asynchronously), the cursor calls the onsuccess event; we store that data in our notes array
            noteCursorRequest.onsuccess = function (e) {
                var cursor = e.target.result;
                if (cursor) {
                    notes.push(cursor.value);
                    cursor.continue();
                }
            };
        };
    }

    function log(message) {
        var logdiv = document.getElementById("dblog");
        logdiv.innerText = message;
    }
    app.start();
})();
